//
//  SFLoginView.swift
//  SwiftForwardWayXu
//
//  Created by 郑程旭 on 2022/1/6.
//

import UIKit

@objc protocol SFLoginViewDelegate {
//    associatedtype
    
    func selectedArea(userRegion: Int) -> Void
    
    func commitLogin(params: [String: Any]?, failure: Int) -> Void
}

class SFLoginView: SFBaseView, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
        
    weak public var delegate: SFLoginViewDelegate?
    
    private let areaArr = ["广西","全国","十五省","河北廊坊"]
    private let roleArr = ["筛查员","质控员","校医","班主任"]
    
    //MARK: - 初始化视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //Mark: - 创建子视图
    private func configSubviews() -> Void {
        self.addSubview(self.iconImgv)
        iconImgv.snp.makeConstraints { make in
            make.width.equalTo(200)
            make.height.equalTo(55)
            make.centerX.equalTo(self).offset(0)
            make.top.equalTo(125)
        }
        
        self.addSubview(self.versionLbl)
        versionLbl.snp.makeConstraints { make in
            make.bottom.equalTo(-50)
            make.centerX.equalTo(self).offset(0)
        }
        
        self.addSubview(self.loginBtn)
        loginBtn.snp.makeConstraints { make in
            make.width.equalTo(290)
            make.height.equalTo(40)
            make.centerX.equalTo(self).offset(0)
            make.top.equalTo(self.iconImgv.snp.bottom).offset(275)
        }
        
        self.addSubview(self.findAccountBtn)
        findAccountBtn.snp.makeConstraints { make in
            make.top.equalTo(self.loginBtn.snp.bottom).offset(20)
            make.right.equalTo(self.loginBtn).offset(0)
        }
        
        self.addSubview(self.passwordTxf)
        passwordTxf.snp.makeConstraints { make in
            make.bottom.equalTo(self.loginBtn.snp.top).offset(-35)
            make.height.equalTo(52)
            make.left.right.equalTo(self.loginBtn)
        }
        
        self.addSubview(self.accountTxf)
        accountTxf.snp.makeConstraints { make in
            make.bottom.equalTo(self.loginBtn.snp.top).offset(-105)
            make.height.equalTo(52)
            make.left.right.equalTo(self.loginBtn)
        }
        
        self.addSubview(self.roleTxf)
        roleTxf.leftMargin = 0
        roleTxf.snp.makeConstraints { make in
            make.height.equalTo(52)
            make.width.equalTo(120)
            make.right.equalTo(self.loginBtn)
            make.bottom.equalTo(self.loginBtn.snp.top).offset(-165)
        }

        self.addSubview(self.areaTxf)
        areaTxf.snp.makeConstraints { make in
            make.left.equalTo(self.loginBtn)
            make.right.equalTo(self.roleTxf.snp.left).offset(-25)
            make.height.centerY.equalTo(self.roleTxf)
        }
        
        self.addSubview(self.areaTableView)
        areaTableView.snp.makeConstraints { make in
            make.left.right.equalTo(self.areaTxf)
            make.height.equalTo(165)
            make.top.equalTo(self.areaTxf.snp.bottom).offset(-10)
        }
        
        self.addSubview(self.roleTableView)
        roleTableView.snp.makeConstraints { make in
            make.right.equalTo(self.roleTxf)
            make.left.equalTo(self.roleTxf).offset(-15)
            make.height.equalTo(165)
            make.top.equalTo(self.roleTxf.snp.bottom).offset(-10)
        }
    }
    
    lazy var iconImgv: UIImageView = {
        let iconImgv = UIImageView.init(image: UIImage.init(named: "loginimg"))
        return iconImgv
    }()
    
    lazy var versionLbl: UILabel = {
        let versionLbl = UILabel.init()
        versionLbl.font = .systemFont(ofSize: 13)
        versionLbl.textColor = .lightGray
        let versionStr: String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        versionLbl.text = "当前版本：\(versionStr)"
        return versionLbl
    }()
    
    lazy var loginBtn: UIButton = {
        let loginBtn = UIButton.init(type: UIButton.ButtonType.custom)
        loginBtn.backgroundColor = kTintColor
        loginBtn.setTitle("登录", for: UIControl.State.normal)
        loginBtn.setTitleColor(.white, for: UIControl.State.normal)
        loginBtn.titleLabel?.font = .systemFont(ofSize: 18)
        loginBtn.layer.cornerRadius = 20
        loginBtn.layer.masksToBounds = true
        loginBtn.addTarget(self, action: #selector(loginAction), for: UIControl.Event.touchUpInside)
        return loginBtn
    }()

    lazy var findAccountBtn: UIButton = {
        let findAccountBtn = UIButton.init(type: UIButton.ButtonType.custom)
        let title = NSMutableAttributedString.init(string: "如何获得登录账号?")
        let range = NSMakeRange(0, title.length)
        title.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
        title.addAttribute(NSAttributedString.Key.underlineColor, value: kTintColor, range: range)
        title.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 11), range: range)
        findAccountBtn.setAttributedTitle(title, for: UIControl.State.normal)
        findAccountBtn.setTitleColor(kTintColor, for: UIControl.State.normal)
        findAccountBtn.addTarget(self, action: #selector(findAccountAction), for: UIControl.Event.touchUpInside)
        return findAccountBtn
    }()
    
    lazy var passwordTxf: SFLoginTextField = {
        
        var eyeBtn = UIButton.init(type: UIButton.ButtonType.custom)
        eyeBtn.setImage(UIImage.init(named: "eyeClosed"), for: UIControl.State.normal)
        eyeBtn.setImage(UIImage.init(named: "eyeOpen"), for: UIControl.State.selected)
        eyeBtn.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
        eyeBtn.adjustsImageWhenHighlighted = false
        eyeBtn.addTarget(self, action: #selector(changeSecureTextEntry), for: UIControl.Event.touchUpInside)
        
        let passwordTxf = SFLoginTextField.init(placeHoleder: "请输入密码", isSecureTextEntry: true, fontSize: 16)
        passwordTxf.inputTxf.delegate = self
        passwordTxf.inputTxf.rightViewMode = UITextField.ViewMode.always
        passwordTxf.inputTxf.rightView = eyeBtn
        
        return passwordTxf
    }()
    
    lazy var accountTxf: SFLoginTextField = {
        let accountTxf = SFLoginTextField.init(placeHoleder: "请输入账号", isSecureTextEntry: false, fontSize: 16)
        accountTxf.inputTxf.delegate = self
        return accountTxf
    }()
    
    lazy var areaTxf: SFLoginTextField = {
        
        var arrowImgv = UIImageView.init(image: UIImage.init(named: "arrow_down"))
        arrowImgv.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
        
        let areaTxf = SFLoginTextField.init(placeHoleder: "请选择地区", isSecureTextEntry: false, fontSize: 15)
        areaTxf.inputTxf.delegate = self
        areaTxf.inputTxf.rightViewMode = UITextField.ViewMode.always
        areaTxf.inputTxf.rightView = arrowImgv
        
        return areaTxf
    }()
    
    lazy var roleTxf: SFLoginTextField = {

        var arrowImgv = UIImageView.init(image: UIImage.init(named: "arrow_down"))
        arrowImgv.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)

        let roleTxf = SFLoginTextField.init(placeHoleder: "请选择角色", isSecureTextEntry: false, fontSize: 15)
        roleTxf.inputTxf.delegate = self
        roleTxf.inputTxf.rightViewMode = UITextField.ViewMode.always
        roleTxf.inputTxf.rightView = arrowImgv

        return roleTxf
    }()
    
    lazy var areaTableView: SFBaseTableView = createChooseView()
    
    lazy var roleTableView: SFBaseTableView = createChooseView()
    
    //MARK: - 创建选择视图
    func createChooseView() -> SFBaseTableView {
        let tableView = SFBaseTableView.init(frame: CGRect.zero, style: UITableView.Style.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.alpha = 0
        tableView.isHidden = true
        tableView.layer.borderColor = UIColor.lightGray.cgColor
        tableView.layer.borderWidth = 1;
        tableView.layer.masksToBounds = true
        tableView.layer.cornerRadius = 5
        return tableView
    }
    
    //MARK: - UITableViewDatasource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == areaTableView {
            return areaArr.count
        } else {
            return roleArr.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: SFBaseTableView.cellId, for: indexPath)
//        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        
        if tableView == areaTableView {
            cell.textLabel?.text = areaArr[indexPath.row]
        } else {
            cell.textLabel?.text = roleArr[indexPath.row]
        }

        return cell
    }
    
    //MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.statusForChooseView(tableView: tableView as! SFBaseTableView, isHidden: true)
        if (tableView == areaTableView) {
            areaTxf.inputTxf.text = areaArr[indexPath.row]
            areaTxf.inputTxf.font = .systemFont(ofSize: 18)
            delegate?.selectedArea(userRegion: indexPath.row)
        } else {
            roleTxf.inputTxf.text = roleArr[indexPath.row]
            roleTxf.inputTxf.font = .systemFont(ofSize: 18)
        }
    }
    
    //MARK: - UITextFieldDelegate
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        var canEdit = true
        
        if (textField == areaTxf.inputTxf) {
            self.statusForChooseView(tableView: areaTableView, isHidden: false)
            (roleTableView.isHidden == false) ? (self.statusForChooseView(tableView: roleTableView, isHidden: true)): nil
            canEdit = false
            self.endEditing(true)
        } else if (textField == roleTxf.inputTxf) {
            self.statusForChooseView(tableView: roleTableView, isHidden: false)
            (areaTableView.isHidden == false) ? (self.statusForChooseView(tableView: areaTableView, isHidden: true)): nil
            canEdit = false
            self.endEditing(true)
        } else {
            (areaTableView.isHidden == false) ? (self.statusForChooseView(tableView: areaTableView, isHidden: true)): nil
            (roleTableView.isHidden == false) ? (self.statusForChooseView(tableView: roleTableView, isHidden: true)): nil
        }
        
        return canEdit
    }
    
    //MARK: - 点击空白
    override func tapGestureAction() {
        super.tapGestureAction()
        hiddenForChooseView()
    }
    
    //MARK: - 选择视图显示/隐藏动画
    private func statusForChooseView(tableView: SFBaseTableView, isHidden: Bool) -> Void {
        if (isHidden == true) {
            UIView.animate(withDuration: 0.3) {
                tableView.alpha = 0
            } completion: { _ in
                tableView.isHidden = true
            }
        } else {
            self.endEditing(true)
            tableView.isHidden = false
            UIView.animate(withDuration: 0.3) {
                tableView.alpha = 1
            }
        }
    }
    
    //MARK: - 隐藏所有选择视图
    private func hiddenForChooseView() -> Void {
        self.endEditing(true)
        (areaTableView.isHidden == false) ? (self.statusForChooseView(tableView: areaTableView, isHidden: true)): nil
        (roleTableView.isHidden == false) ? (self.statusForChooseView(tableView: roleTableView, isHidden: true)): nil
    }

    //MARK: - 安全输入设置
    @objc private func changeSecureTextEntry(sender: UIButton) -> Void {
        passwordTxf.inputTxf.isSecureTextEntry = sender.isSelected
        sender.isSelected = !sender.isSelected
    }
    
    //MARK: - 登录
    @objc private func loginAction() -> Void {
        NSLog("登录")
        self.hiddenForChooseView()

        guard let _ = areaTxf.inputTxf.text else {
            delegate?.commitLogin(params: nil, failure: 1)
            return
        }
        
        guard let _ = roleTxf.inputTxf.text else {
            delegate?.commitLogin(params: nil, failure: 2)
            return
        }
        
        guard let _ = accountTxf.inputTxf.text else {
            delegate?.commitLogin(params: nil, failure: 3)
            return
        }
        
        guard let _ = passwordTxf.inputTxf.text else {
            delegate?.commitLogin(params: nil, failure: 4)
            return
        }
        
        var params: [String: Any] = [:]
        params["phone"] = accountTxf.inputTxf.text!
        params["pw"] = passwordTxf.inputTxf.text!
        params["v"] = "iOS:v\(versionLbl.text!)"
        delegate?.commitLogin(params: params, failure: 0)
        
    }
    
    
    
    //MARK: - 如何获得登录账号
    @objc private func findAccountAction() -> Void {
        self.hiddenForChooseView()
        SFLoginGetAccountView.init().showGetAccountView(superView: self)
    }

}

class SFLoginTextField: UIView, UITextFieldDelegate {
        
    var leftMargin: CGFloat? {
        didSet {
            inputTxf.snp.updateConstraints { make in
                make.left.equalTo(leftMargin!)
            }
        }
    }
    
    //MARK: - 初始化视图
    init(placeHoleder: String, isSecureTextEntry: Bool, fontSize: CGFloat) {
        
        super.init(frame: CGRect.zero)
                
        self.addSubview(self.lineView)
        lineView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.height.equalTo(1)
            make.bottom.equalTo(0)
        }
        
        self.addSubview(self.inputTxf)
        inputTxf.placeholder = placeHoleder
        inputTxf.font = .systemFont(ofSize: fontSize)
        inputTxf.isSecureTextEntry = isSecureTextEntry
        inputTxf.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.right.equalTo(0)
            make.bottom.equalTo(-1)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("")
    }
        
    //MARK: - 创建子视图
    lazy var lineView: UIView = {
        let lineView = UIView.init()
        lineView.backgroundColor = kHexColor(hex: 0xE6E6E6, alpha: 1)
        return lineView
    }()

    lazy var inputTxf: UITextField = {
        let inputTxf = UITextField.init()
        inputTxf.clearButtonMode = UITextField.ViewMode.whileEditing
        return inputTxf
    }()
    
}
